package com.zhanglu.fun.services.chatroom.security;

import java.util.Arrays;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zhanglu.fun.tookit.jwt.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.stereotype.Component;

import com.zhanglu.fun.services.chatroom.config.SecurityConfig;
import com.zhanglu.fun.services.chatroom.login.TokenService;

@Component
public class AuthLogoutHandler implements LogoutHandler {

    @Autowired
    private TokenService tokenService;

    @Override
    public void logout(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) {
        Arrays.stream(httpServletRequest.getCookies()).filter(c -> JwtUtil.COOKIE_AUTH.equalsIgnoreCase(c.getName())).findFirst().map(c -> {
            tokenService.deleteToken(c.getValue());
            return null;
        }).orElseGet(null);

    }
}
